﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.Skins;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using DevExpress.Utils.Design;
using System.Collections;
using System.Data.SqlTypes;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using DevExpress.XtraRichEdit.Import.Html;
using DevExpress.XtraRichEdit.Layout;
using DevExpress.XtraRichEdit.API.Word;
using System.Web.UI.WebControls;
using DevExpress.XtraBars.Ribbon;

namespace SmartFrame_DataCollect
{
    public partial class ucMailTree : BaseControl
    {
        public event DataSourceChangedEventHandler DataSourceChanged;
        public event MouseEventHandler ShowMenu;
        bool allowDataSourceChanged = false;
        public frmMain mainForm;

        public ucMailTree()
        {
            InitializeComponent();
            treeList1.RowHeight = Math.Max(Convert.ToInt32(treeList1.Font.GetHeight()), icFolders.ImageSize.Height) + 5;
        }

        public ucMailTree(frmMain _mainForm)
        {
            InitializeComponent();
            treeList1.RowHeight = Math.Max(Convert.ToInt32(treeList1.Font.GetHeight()), icFolders.ImageSize.Height) + 5;
            mainForm = _mainForm;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //if (!DesignTimeTools.IsDesignMode)
            //    treeList1.FocusedNode = treeList1.Nodes[0].Nodes[0];
        }
        public void NewTreeData(List<DataRowCollection> rows)
        {
            //treeList2.ClearNodes();
            treeList2.DataSource = null;

            DataTable dt3 = new DataTable();
            dt3.Columns.Add("t3",typeof(string));
            dt3.Columns.Add("Id",typeof(int));
            dt3.Columns.Add("parentId", typeof(int));

            DataRow dr = dt3.NewRow();
            dr["t3"] = "333";
            dr["Id"] = 1;
            dr["parentId"] = 0;
            dt3.Rows.Add(dr);
            treeList2.KeyFieldName = "Id";
            treeList2.ParentFieldName = "parentId";

            treeList2.DataSource = dt3;

            //if (rows.Count > 0)
            //{
            //    TreeListNode sbType;
            //    foreach (DataRowCollection item in rows)
            //    {
            //        sbType = treeList2.AppendNode(new object[] { item[0]["EquipmentTypeName"] }, null);
            //        foreach (DataRow itemTow in item)
            //            treeList2.AppendNode(new object[] { itemTow["EquipmentName"].ToString() + " 【" + itemTow["EquipmentCode"].ToString() + "】", itemTow["EquipmentID"] }, sbType);
            //        treeList2.ExpandAll();

            //        allowDataSourceChanged = true;
            //    }
            //}
            //else
            //{
            //    //defaultTreeData("暂无采集设备");
            //}
        }

        public List<DataRowCollection> SelectTreeData(string userDbName, List<string> EquipmentTypeNames = null, int c = 0, List<DataRowCollection> dataList = null)
        {
            string SqlString = string.Empty;
            if (EquipmentTypeNames == null || dataList == null)
            {
                EquipmentTypeNames = new List<string>();
                dataList = new List<DataRowCollection>();
            }
            if (EquipmentTypeNames.Count <= 0 && !string.IsNullOrEmpty(userDbName))
            {
                SqlString = "SELECT EquipmentTypeName FROM " + userDbName + ".dbo.Ba_EquipmentType as baetype LEFT JOIN " + userDbName + ".dbo.Ba_Equipment as bae ON baetype.EquipmentTypeID = bae.UpID WHERE IsCJ = 1 GROUP BY EquipmentTypeName";
                DataRowCollection rows = CommonSql._Query(SqlString, new Dictionary<string, object>()).Tables[0].Rows;
                if (rows.Count > 0)
                {
                    foreach (DataRow item in rows)
                    {
                        EquipmentTypeNames.Add(item["EquipmentTypeName"].ToString());
                    }
                    c = 1;
                    SelectTreeData(userDbName, EquipmentTypeNames, c, dataList);
                }
                else
                {
                    return dataList;
                }
            }
            else if (c <= EquipmentTypeNames.Count() && EquipmentTypeNames.Count() > 0)
            {
                SqlString = "SELECT EquipmentTypeName,EquipmentCode,EquipmentName,EquipmentID FROM " + userDbName + ".dbo.Ba_EquipmentType as baetype LEFT JOIN " + userDbName + ".dbo.Ba_Equipment as bae ON baetype.EquipmentTypeID = bae.UpID WHERE IsCJ = 1 AND EquipmentTypeName=@EquipmentTypeName;";
                Dictionary<string, object> Sqlpar = new Dictionary<string, object>();
                Sqlpar.Add("EquipmentTypeName", EquipmentTypeNames[c - 1]);
                TreeListNode sbType = treeList1.AppendNode(new object[] { EquipmentTypeNames[c - 1] }, null);
                DataRowCollection rows = CommonSql._Query(SqlString, Sqlpar).Tables[0].Rows;
                c++;
                dataList.Add(rows);
                SelectTreeData(userDbName, EquipmentTypeNames, c, dataList);
            }
            return dataList;
        }

        public void defaultTreeData(string mes)
        {
            treeList1.ClearNodes();
            TreeListNode sbType = treeList1.AppendNode(new object[] { mes }, null);
            treeList1.AppendNode(new object[] { "" }, sbType);
            treeList1.ExpandAll();
            if (!DesignTimeTools.IsDesignMode)
                CreateMessagesList(treeList1.Nodes);
            allowDataSourceChanged = true;
        }

        void CreateMessagesList(TreeListNodes nodes)
        {
            foreach (TreeListNode node in nodes)
            {
                CreateMessagesForNode(node);
                CreateMessagesList(node.Nodes);
                if (GetNodeMailFolder(node) >= (int)MailFolder.Custom)
                {
                    List<TreeListNode> children = new List<TreeListNode>();
                    children.Add(node);
                    GetAllChildren(node, children);
                    List<Message> list = new List<Message>();
                    foreach (var n in children)
                    {
                        list.AddRange(((IEnumerable<Message>)n.GetValue(colData)));
                    }
                    node.SetValue(colData, list);

                }

            }
        }
        void GetAllChildren(TreeListNode node, List<TreeListNode> list)
        {
            if (!node.HasChildren) return;
            foreach (TreeListNode child in node.Nodes)
            {
                list.Add(child);
                GetAllChildren(child, list);
            }
        }
        internal MailType GetNodeMailType(TreeListNode node)
        {
            //return (MailType)node.GetValue(colType);
            return MailType.Inbox;
        }
        internal int GetNodeMailFolder(TreeListNode node)
        {
            //return (int)node.GetValue(colFolder);
            return 0;
        }
        void CreateMessagesForNode(TreeListNode node)
        {
            List<Message> messages = new List<Message>();
            MailType mailType = GetNodeMailType(node);
            int mailFolder = GetNodeMailFolder(node);
            foreach (Message message in DataHelper.Messages)
            {
                if (message.MailType == mailType &&
                    (message.MailFolder == mailFolder || mailFolder == (int)MailFolder.All || mailType == MailType.Deleted) &&
                    !message.Deleted)
                    messages.Add(message);
            }
            node.SetValue(colData, messages);
        }
        protected override void LookAndFeelStyleChanged()
        {
            base.LookAndFeelStyleChanged();
            Color controlColor = CommonSkins.GetSkin(DevExpress.LookAndFeel.UserLookAndFeel.Default).Colors.GetColor("Control");
            treeList1.Appearance.Empty.BackColor = controlColor;
            treeList1.Appearance.Row.BackColor = controlColor;
            SetFocusedColor(CommonSkins.GetSkin(DevExpress.LookAndFeel.UserLookAndFeel.Default));
        }
        void SetFocusedColor(Skin skin)
        {
            if ("|Office 2016 Colorful|".IndexOf(skin.Name) > 0)
            {
                treeList1.Appearance.FocusedRow.BackColor = skin.Colors.GetColor("HideSelection");
            }
            else treeList1.Appearance.FocusedRow.BackColor = skin.Colors.GetColor("Highlight");
        }
        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            //RaiseDataSourceChanged(e.Node);
        }
        void RaiseDataSourceChanged(TreeListNode node)
        {
            if (DataSourceChanged != null && allowDataSourceChanged)
                DataSourceChanged(treeList1, new DataSourceChangedEventArgs(GetNodeCaption(node), node.GetValue(colData), node.GetValue(colType)));
        }
        string GetNodeCaption(TreeListNode node)
        {
            string ret = string.Format("{0}", node.GetValue(colName));
            while (node.ParentNode != null)
            {
                node = node.ParentNode;
                ret = string.Format("{0} - {1}", node.GetValue(colName), ret);
            }
            return ret;
        }
        private void treeList1_CustomDrawNodeCell(object sender, CustomDrawNodeCellEventArgs e)
        {
            if (DesignTimeTools.IsDesignMode) return;
            if (e.Column == colName)
            {
                string textColor = GetHtmlTextColor(treeList1.FocusedNode.Equals(e.Node));
                object textValue = e.Node.GetValue(colName);
                e.CellText = string.Format("<Color={1}>{0}", textValue, textColor);
                if (e.Node.ParentNode == null || !(DataHelper.ShowAllMessageCount || DataHelper.ShowUnreadMessageCount)) return;
                List<Message> list = e.Node.GetValue(colData) as List<Message>;
                //int unread = GetUnreadMessagesCount(list);
                if (DataHelper.ShowUnreadMessageCount)
                {
                    if (DataHelper.ShowAllMessageCount)
                        e.CellText = string.Format("<Color={5}><b>{0}</b><Size=-1><Color={2}> [{1}/<Color={4}>{3}<Color={2}>]", textValue, 0, ColorHelper.HtmlQuestionColor, list.Count, ColorHelper.HtmlWarningColor, textColor);
                    else
                        e.CellText = string.Format("<Color={3}><b>{0}</b><Size=-1><Color={2}> [{1}]", textValue, 0, ColorHelper.HtmlQuestionColor, textColor);
                }
                else
                {
                    if (DataHelper.ShowAllMessageCount && list.Count > 0)
                        e.CellText = string.Format("<Color={3}>{0}<Size=-1><Color={2}> [{1}]", textValue, list.Count, ColorHelper.HtmlWarningColor, textColor);
                }
            }
        }
        static string GetHtmlTextColor(bool focused)
        {
            if (focused)
                return ColorHelper.HtmlHighlightTextColor;
            return AllowControlTextColor ? ColorHelper.HtmlControlTextColor : ColorHelper.HtmlControlTextColor2;
        }
        static bool AllowControlTextColor
        {
            get
            {
                return DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveSkinName != "Glass Oceans";
            }
        }
        int GetUnreadMessagesCount(List<Message> list)
        {
            return list.Count(p => p.IsUnread);
        }
        internal bool IsDeletedFolderFocused() { return treeList1.FocusedNode != null && GetNodeMailFolder(treeList1.FocusedNode) == (int)MailFolder.Deleted; }
        static int CustomFolderId = (int)MailFolder.Custom;
        internal void CreateNewFolder()
        {
            if (treeList1.FocusedNode == null || IsDeletedFolderFocused()) return;
            var node = treeList1.FocusedNode.Nodes.Add(new object[] { Properties.Resources.NewFolder, MailType.Inbox, CustomFolderId++, 9, new List<Message>() });

            treeList1.FocusedNode = node;
            StartEditing();

        }
        internal void StartEditing()
        {
            if (treeList1.FocusedNode == null || IsDeletedFolderFocused()) return;
            treeList1.OptionsBehavior.Editable = true;
            treeList1.VisibleColumns[0].OptionsColumn.AllowFocus = true;
            treeList1.FocusedColumn = treeList1.VisibleColumns[0];
            treeList1.ShowEditor();
        }
        private void treeList1_HiddenEditor(object sender, EventArgs e)
        {
            treeList1.OptionsBehavior.Editable = false;
            treeList1.VisibleColumns[0].OptionsColumn.AllowFocus = false;
            treeList1.ClearFocusedColumn();
        }
        internal void RefreshTreeList()
        {
            treeList1.LayoutChanged();
        }
        private void treeList1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && ShowMenu != null) ShowMenu(sender, e);
        }

        internal void UpdateTreeViewMessages()
        {
            CreateMessagesList(treeList1.Nodes);
            RefreshTreeList();
            RaiseDataSourceChanged(treeList1.FocusedNode);
        }


        private void treeList1_DragEnter(object sender, DragEventArgs e)
        {
            DragSelection dragSelection = e.Data.GetData(typeof(DragSelection)) as DragSelection;
            if (dragSelection == null) return;
            e.Effect = DragDropEffects.Move;
        }

        private void treeList1_DragDrop(object sender, DragEventArgs e)
        {
            DragSelection dragSelection = e.Data.GetData(typeof(DragSelection)) as DragSelection;
            if (dragSelection == null) return;
            if (treeList1.DropTaget != null) OnTreeDragDrop(treeList1.DropTaget, dragSelection);
        }
        public event UCTreeDragDropEventHandler UCTreeDragDrop;
        void OnTreeDragDrop(TreeListNode node, DragSelection selection)
        {
            if (UCTreeDragDrop != null) UCTreeDragDrop(this, new UCTreeDragDropEventArgs() { Node = node, Selection = selection });

        }

        private void treeList1_CustomNodeCellEditForEditing(object sender, GetCustomNodeCellEditEventArgs e)
        {
            e.RepositoryItem = repositoryItemTextEdit1;
        }

        private void treeList1_MouseClick(object sender, MouseEventArgs e)
        {
            MyTreeList tree = sender as MyTreeList;
            if (tree.FocusedNode != null)
            {
                var treeFocusNode = tree.FocusedNode;
                var equipID = treeFocusNode.GetValue(1);
                if(equipID!=null)
                {
                    //更新界面
                    DeviceDetails deviceModule = mainForm.modulesNavigator.CurrentModule as DeviceDetails;
                    deviceModule.curEuipID = equipID.ToString();
                    deviceModule.InitControlConfig();
                }
            }
        }
    }
    public delegate void UCTreeDragDropEventHandler(object sender, UCTreeDragDropEventArgs e);
    public class UCTreeDragDropEventArgs : EventArgs
    {
        public TreeListNode Node { get; set; }
        public DragSelection Selection { get; set; }
    }
    public class MyTreeList : TreeList
    {
        public DevExpress.XtraTreeList.Handler.StateData StateData
        {
            get
            {
                return this.Handler.StateData;
            }
        }
        protected internal TreeListNode DropTaget
        {
            get
            {
                if (StateData != null && StateData.DragInfo != null && StateData.DragInfo.RowInfo != null) return StateData.DragInfo.RowInfo.Node;
                return null;
            }
        }
    }
}
